package com.memory.test.service.impl;


import com.memory.test.dao.WordsDao;
import com.memory.test.dao.WordsMapperCustom;
import com.memory.test.mbg.mapper.MWordsMapper;
import com.memory.test.mbg.model.MWords;
import com.memory.test.nosql.document.EsWords;
import com.memory.test.nosql.repository.EsWordsRepository;
import com.memory.test.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class WordServiceImpl implements WordService {
    @Autowired
    private WordsMapperCustom mWordsMapper;

    @Autowired
    private WordsMapperCustom wordsDao;
    @Autowired
    private EsWordsRepository productRepository;
    @Override
    public MWords selectWord(String word) {
        return mWordsMapper.selectWord(word);
    }

    @Override
    public void addWord(MWords word1) {
        mWordsMapper.insert(word1);
    }

    @Override
    public int importAll() {
        List<EsWords> esProductList = wordsDao.getAllEsProductList(null);
        Iterable<EsWords> esProductIterable = productRepository.saveAll(esProductList);
        Iterator<EsWords> iterator = esProductIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    @Override
    public void delete(Long id) {
        productRepository.deleteById(id);
    }

    @Override
    public EsWords create(Long id) {
        EsWords result = null;
        List<EsWords> esProductList = wordsDao.getAllEsProductList(id);
        if (esProductList.size() > 0) {
            EsWords esProduct = esProductList.get(0);
            result = productRepository.save(esProduct);
        }
        return result;
    }

    @Override
    public void delete(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<EsWords> esProductList = new ArrayList<>();
            for (Long id : ids) {
                EsWords esProduct = new EsWords();
                esProduct.setId(id);
                esProductList.add(esProduct);
            }
            productRepository.deleteAll(esProductList);
        }
    }

    @Override
    public Page<EsWords> search(String english, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return productRepository.findByChineseOrEnglishOrDescribetion(english, english, english, pageable);
    }
}
